#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/6/8 23:22
# @Author : linjinting
# @Project : custom_protocol
# @File : logger_distribute.py
# @Software: PyCharm


import logging
from protocol_message import parse_to_msg
from TTLLogging import create_logger


class UIHandle(logging.StreamHandler):
    def __init__(self, widget):
        logging.StreamHandler.__init__(self, widget)
        self.formatter = logging.Formatter(
            "[%(asctime)s] [%(levelname)s] %(name)s: %(message)s")

        # self.formatter = logging.Formatter(
        #     "[%(asctime)s] %(levelname)s in %(name)s-%(module)s at %(lineno)d: %(message)s")


class LoggerDistribute(object):
    def __init__(self, browser, logger=None, callback=None):
        self.m_browser = browser
        if logger is None:
            self.m_logger = create_logger('MsgDistribute.default')
        else:
            self.m_logger = logger

        handle = UIHandle(self)
        self.m_logger.addHandler(handle)

    def write(self, msg):
        try:
            self.m_browser.insertPlainText(msg)
        except:
            pass

    def log(self, **kwargs):
        # print('log', msg, level)
        msg = kwargs.get('msg')
        data = kwargs.get('data')
        if data:
            if isinstance(data, bytes):
                data = data.hex()
            msg += '------------------------- [HEX] %s\n' % data
        level = kwargs.get('level', 'None')
        caller = kwargs.get('caller')
        laddr = kwargs.get('laddr')
        if laddr:
            msg += '------------------------- laddr=%s' % str(laddr)
        raddr = kwargs.get('raddr')
        if raddr:
            msg += '| raddr=%s' % str(raddr)

        if level == 'info':
            self.m_logger.info(msg)
        elif level == 'debug':
            # msg = msg + 'at %s' % str(caller)
            self.m_logger.debug(msg)
        elif level == 'error':
            msg = msg + '\n------------------------- @ %s' % str(caller)
            self.m_logger.error(msg)
        else:
            return

    def parse(self, msg, channel, side):
        self.m_logger.info(parse_to_msg(msg, channel, side))
